package hr.functional.teststeps;

import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
import cucumber.runtime.PendingException;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

import java.net.URL;
import java.util.List;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Created with IntelliJ IDEA.
 * User: VMoskalenko
 * Date: 22.06.12
 * Time: 23:29
 */
public class SeleniumSteps {

    private static final Logger logger = Logger.getLogger(SeleniumSteps.class);

    WebDriver driver;

    @When("^I access \"([^\"]*)\" page$")
    public void I_have_access_page(String service) {
        driver = new HtmlUnitDriver();
        driver.get("http://localhost:8888/hr/" + service);
    }

    @Then("^stuff result page contains$")
    public void stuff_result_page_contains(List<Employee> employees) {
        int index = 1;
        for (Employee employee : employees) {
            assertThat(fieldValue("fn", index), is(employee.firstName));
            assertThat(fieldValue("ln", index), is(employee.lastName));
            assertThat(fieldValue("jt", index++), is(employee.jobTitle));
        }
    }

    @When("^click \"([^\"]*)\" row where lastName is \"([^\"]*)\"$")
    public void click_row_where_is(String elementName, String fieldValue) {
        driver.findElement(By.id(elementName+fieldValue)).click();
    }

    @When("^I upload \"([^\"]*)\" file$")
    public void I_upload_file(String fileName) {
        URL csvFileUrl = getClass().getClassLoader().getResource(fileName);
        logger.info("CSV File: " + csvFileUrl.toExternalForm());
        driver.findElement(By.id("upload-file")).sendKeys(csvFileUrl.toExternalForm());
        driver.findElement(By.id("upload-button")).submit();
    }

    public String fieldValue(String prefix, int index) {
        return driver.findElement(By.id(prefix + index)).getText();
    }

    @When("^I enter \"([^\"]*)\" in \"([^\"]*)\" field on create page$")
    public void I_enter_in_field_on_create_page(String fieldValue, String fieldName) {
        driver.findElement(By.name(fieldName)).sendKeys(fieldValue);
    }

    @When("^click the \"([^\"]*)\" button$")
    public void click_the_button(String name) {
        // Express the Regexp above with the code you wish you had
        driver.findElement(By.name(name)).submit();
    }

    public static class Employee {
        String firstName;
        String lastName;
        String jobTitle;
    }
}
